﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using AcctrueWMS.Foundation.DAL;
using System.Xml;
namespace AcctruePMS.Bll.Manager
{
    public class ProjectChangeLogManager
    {
        /// <summary>
        /// 根据项目ID获取对应状态变更日志
        /// </summary>
        /// <param name="projectGUID"></param>
        /// <returns></returns>
        public DataTable GetLogByProjectGUID(string projectGUID)
        {

            IDataParameter[] pars = { DBFactory.NewParameter("@projectGUID", projectGUID) };
            string sql = "select projectGUID, changeBefore, changeAfter,convert(nvarchar(100),changeTime,120) as changeTime, executor, changeColumn from projectChangeLog where projectGUID=@projectGUID order by changeTime";
            DataTable dt = WMSqlExcuter.ExecuteDataTable(sql,pars);
            if (dt.Rows.Count > 0) {
                foreach (DataRow row in dt.Rows)
                {
                   row["changeBefore"] = ChangeColumnValue(row["changeBefore"].ToString(), row["changeColumn"].ToString());
                   row["changeAfter"] = ChangeColumnValue(row["changeAfter"].ToString(), row["changeColumn"].ToString());
                   row["executor"] = ChangeColumnValue(row["executor"].ToString(), "executor");
                   row["changeColumn"] = ProjectChangeName(row["changeColumn"].ToString());
                }
            
            }
            return dt;
        }

        /// <summary>
        /// 获取项目需要记录日志的字段
        /// </summary>
        /// <returns></returns>
        public DataTable GetProjectNeedRecordLogColumn() {

            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn() { ColumnName="ID", DataType=typeof(string) };//页面控件ID名称
            DataColumn dc1 = new DataColumn() { ColumnName = "columnName", DataType = typeof(string) };//字段名称
            dt.Columns.Add(dc);
            dt.Columns.Add(dc1);
            DataRowCollection drc = dt.Rows;
            GetRecordLogColumnConfig(ref drc,dt);
            return dt;
        }

        /// <summary>
        /// 获取记录日志列的配置信息
        /// </summary>
        /// <param name="drc"></param>
        public void  GetRecordLogColumnConfig(ref DataRowCollection drc,DataTable dt)
        {
            XmlDocument xml = new XmlDocument();
            try
            {
                xml.Load(AppDomain.CurrentDomain.BaseDirectory + @"\SysFiles\ProjectLogConfig\projectLogConfig.xml");
                XmlElement elment = xml.DocumentElement;//获取根元素
                XmlNodeList nodes = elment.ChildNodes;
                foreach (XmlNode node in nodes)
                {
                    DataRow dr = dt.NewRow();
                    dr["ID"] =node.Attributes["ID"].Value;
                    dr["columnName"] = node.Attributes["name"].Value;
                    drc.Add(dr);
                }
             
            }
            catch (Exception e)
            {

                return ;
            }
         
        }

        /// <summary>
        /// 增加项目变更日志
        /// </summary>
        /// <param name="projectGUID">项目ID</param>
        /// <param name="changeBeforeData">变更前的表单数据</param>
        ///  <param name="execNo">执行人</param>
        public void AddProjectChangeLog(string projectGUID,string changeBeforeData,string execNo) {
            String[] splitSign={"(@)"};//控件之间的分隔标志
            String[] splitSign1 = { "(:)" };//列明称和列值的分隔标志
            String[] beforeData=changeBeforeData.Split(splitSign,StringSplitOptions.None);
            DataTable changeAfterData = new ProjectManager().GetProjectByGUIDAndConfig(projectGUID);
            StringBuilder logSql = new StringBuilder();
            int index=0;
            try
            {
                foreach (DataRow row in changeAfterData.Rows)
                {
                    while (index<beforeData.Length)
                    {
                        string[] column = beforeData[index].Split(splitSign1, StringSplitOptions.None);
                        if (row[column[0]].ToString() != column[1])
                        {//需要记录日志
                            logSql.Append("insert into projectChangeLog(projectGUID,changeBefore, ChangeAfter, changeTime, executor, changeColumn) values('");
                            logSql.Append(projectGUID);
                            logSql.Append("','");
                            logSql.Append(column[1]);
                            logSql.Append("','");
                            logSql.Append(row[column[0]].ToString());
                            logSql.Append("','");
                            logSql.Append(DateTime.Now.ToString());
                            logSql.Append("','");
                            logSql.Append(execNo);
                            logSql.Append("','");
                            logSql.Append(column[0]);
                            logSql.Append("');");
                        }
                        index++; 
                    }
                }
                if(logSql.ToString().Length>0)
                WMSqlExcuter.ExecuteNonQuery(logSql.ToString());
            }
            catch (Exception e)
            {

                return;
            }
        }

        /// <summary>
        /// 变更操作的名称
        /// </summary>
        /// <param name="columnName">操作的字段列</param>
        /// <returns></returns>
        public string ProjectChangeName(string columnName) {
            XmlDocument xml = new XmlDocument();
            try
            {
                xml.Load(AppDomain.CurrentDomain.BaseDirectory + @"\SysFiles\ProjectLogConfig\projectLogConfig.xml");
                XmlElement elment = xml.DocumentElement;//获取根元素
                XmlNode node= elment.SelectNodes("column[@name='"+columnName+"']")[0];
                return node.Attributes["displayName"].Value;

            }
            catch (Exception e)
            {

                return "";
            }
        }

        /// <summary>
        /// 获取变更的值
        /// </summary>
        /// <param name="key">变更的键</param>
        /// <param name="columnName">变更的列</param>
        /// <returns></returns>
        public string ChangeColumnValue(string key,string columnName) {
            string statusValue = "select dictValue from dbo.sys_dictionary_items where ( dictName='projectStatus' or dictName='developProjectStatus' ) and dictKey='" + key + "'";
            string userName = "select userName from dbo.userInfo where userNo='" + key+"'";
            string departName = "select departName from departments where wbsCode='"+key+"'";
            switch (columnName)
            {
                case "status":
                    object value=WMSqlExcuter.ExecuteScalar(statusValue);
                    return value == DBNull.Value||value==null ? key : value.ToString();
                case "departWBS":
                    object value1 = WMSqlExcuter.ExecuteScalar(departName);
                    return value1 == DBNull.Value || value1 == null ? key : value1.ToString();
                case "projectManager":
                case "executor":
                case "sales":
                    object value2 = WMSqlExcuter.ExecuteScalar(userName);
                    return value2 == DBNull.Value || value2 == null ? key : value2.ToString();
                default:
                    return key;
            }
        
        }
    }
}
